import { Component, OnInit, ViewChild } from "@angular/core";
import "datatables";
import { ModalDirective } from "ng2-bootstrap/ng2-bootstrap";
import { CompinfoModifyApprService } from "./compinfo-modify.service";
import { ApprInfo } from "./appr-info.class";
import { FormBuilder } from "@angular/forms";
import { DataTablesComponent, DataTablesComponentConfig } from "app/theme/components/dataTables";
import { SearchForm } from "./search-form.class";

@Component({
  selector: 'compinfo-modify-approval',
  templateUrl: 'compinfo-modify.component.html',
  styleUrls: ['compinfo-modify.component.scss'],
  providers: [CompinfoModifyApprService]
})
export class CompinfoModifyApprComponent implements OnInit {
  @ViewChild('apprPassModal') apprPassModal: ModalDirective;
  @ViewChild('apprRejectModal') apprRejectModal: ModalDirective;
  @ViewChild('apprReviewModal') apprReviewModal: ModalDirective;
  @ViewChild('apprDeleteModal') apprDeleteModal: ModalDirective;
  @ViewChild('apprTimeModal') apprTimeModal: ModalDirective;
  @ViewChild(DataTablesComponent) dataTable: DataTablesComponent;

  private apprInfo: ApprInfo = new ApprInfo();
  private _selectdAppr: any = new ApprInfo();
  private originDetailData: any = new ApprInfo();
  private searchForm: SearchForm = new SearchForm();

  private apprUrl = '/water/enterpriseSub/auditModEnterprise';
  private apprInfoUrl = '/water/enterpriseSub/showUpdateDetailsOfEn';
  private apprOrigInfoUrl = '/water/enterpriseSub/getOrEnForAdmin';
  private apprTableUrl = '/water/enterpriseSub/updateList';
  private apprDeleteUrl = '/water/enterpriseSub/delete';
  private downloadTimeUrl = '/water/usersub/printSummaryTableByStageOFM';
  private downloadIdUrl = '/water/usersub/printSummaryTableByIdsOFM';

  private downloadUrlByPoint = '';
  private downloadUrlByStage = '';

  private disableReviewBtn = true;
  private disablePassBtn = true;
  private disableRejectBtn = true;
  private disableDeleteBtn = true;
  private disableDownloadBtn = true;
  private disableDownloadTimeBtn = false;

  private selectedRowData: any[];
  private _errorMsg: string;
  private errorShow = false;

  private dataTablesConfig: DataTablesComponentConfig = new DataTablesComponentConfig();

  constructor(private _fb: FormBuilder, private _service: CompinfoModifyApprService) {
  }

  ngOnInit() {
    this.initDatatables();
  }

  search() {
    this.dataTable.draw();
  }

  private initDatatables() {
    this.dataTablesConfig.ajaxUrl = this.apprTableUrl;
    this.dataTablesConfig.columnsDef = [
      {'name': '公司名', 'id': 'name'},
      {'name': '法人', 'id': 'legalperson'},
      {'name': '联系人', 'id': 'contact'},
      {'name': '联系电话', 'id': 'contacttel'},
      {'name': '行业', 'id': 'industry'},
      {'name': '注册地', 'id': 'registerarea'},
      {'name': '提交时间', 'id': 'submittime', 'orderable': true},
      {'name': '审批时间', 'id': 'verifiedtime','orderable': true},
      {'name': '审核状态', 'id': 'verified'}
    ];
  }

  tableRowSelect(rowData: any[]){
    this.disableAllButtons();
    if (rowData.length > 0) {
      this.disableReviewBtn = rowData.length !== 1;
      this.disablePassBtn = this.disableRejectBtn = rowData[0].verified !== '待审核';
      this.disableDeleteBtn = rowData.length == 0 || rowData[0].verified == '待审核';
      this.disableDownloadBtn = rowData.length == 0 || rowData[0].verified !== '通过';
      if (!this.disableDownloadBtn) {
        this.downloadUrlByPoint = this.downloadIdUrl +'?pkid=' + rowData[0].pkid;
        for (let i = 1; i < rowData.length; i++) {
          let data = rowData[i];
          this.downloadUrlByPoint = this.downloadUrlByPoint + ',' + data.pkid;
        }
        this.downloadUrlByPoint += '&type=企业信息变更';
      }

      this.selectedRowData = rowData;
    }
  }

  handleError(e:any){
    if(e.type == 'error'){
      this.errorShow = true;
    }
  }

  private disableAllButtons() {
    this.disableReviewBtn = this.disablePassBtn = this.disableRejectBtn = this.disableDeleteBtn = true;
  }

  review() {
    let pkid = this.selectedRowData[0].pkid;
    this.loadInfo(pkid);
    this.getCompOriginInfo(pkid);
  }

  private loadInfo(pkid: string) {
    this._selectdAppr = new ApprInfo();
    this._service.reviewAppr(this.apprInfoUrl, pkid)
      .then(res => {
        if (res.status === 'success') {
          this._selectdAppr = res.data;
          // setTimeout(this.annotated(), 1000);
          this.apprReviewModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  private getCompOriginInfo(pkid:string){
    this.originDetailData = new ApprInfo();
    this._service.getCompOriginInfo(this.apprOrigInfoUrl, pkid)
      .then(res => {
        if (res.status === 'success') {
          this.originDetailData = res.data;
          this.apprReviewModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  // annotated() {
  //   if (this._selectdAppr.enterpriseinfo.verified == "待审核") {
  //     if (this.originDetailData.enterpriseinfo.name != this._selectdAppr.enterpriseinfo.name) {
  //       jQuery('#newName').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newName').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.registerarea != this._selectdAppr.enterpriseinfo.registerarea) {
  //       jQuery('#newRegisterarea').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newRegisterarea').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.registeredcapital != this._selectdAppr.enterpriseinfo.registeredcapital) {
  //       jQuery('#newRegisteredcapital').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newRegisteredcapital').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.website != this._selectdAppr.enterpriseinfo.website) {
  //       jQuery('#newWebsite').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newWebsite').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.postcode != this._selectdAppr.enterpriseinfo.postcode) {
  //       jQuery('#newPostcode').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newPostcode').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.permitid != this._selectdAppr.enterpriseinfo.permitid) {
  //       jQuery('#newPermitid').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newPermitid').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.contact != this._selectdAppr.enterpriseinfo.contact) {
  //       jQuery('#newContact').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newContact').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.contacttel != this._selectdAppr.enterpriseinfo.contacttel) {
  //       jQuery('#newContacttel').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newContacttel').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.email != this._selectdAppr.enterpriseinfo.email) {
  //       jQuery('#newIds').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newIds').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.address != this._selectdAppr.enterpriseinfo.address) {
  //       jQuery('#newAddress').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newAddress').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.certificateid != this._selectdAppr.enterpriseinfo.certificateid) {
  //       jQuery('#newCertificateid').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newCertificateid').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.entertype != this._selectdAppr.enterpriseinfo.entertype) {
  //       jQuery('#enterpriseSub_entertype').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#enterpriseSub_entertype').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.establishtime != this._selectdAppr.enterpriseinfo.establishtime) {
  //       jQuery('#newEstablishtime').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newEstablishtime').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.industry != this._selectdAppr.enterpriseinfo.industry) {
  //       jQuery('#newIndustry').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newIndustry').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.legalperson != this._selectdAppr.enterpriseinfo.legalperson) {
  //       jQuery('#newLegalperson').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newLegalperson').css('color', '#000000');
  //     }
  //     if (this.originDetailData.enterpriseinfo.license != this._selectdAppr.enterpriseinfo.license) {
  //       jQuery('#newLicense').css('color', '#93D4E7');
  //     }else{
  //       jQuery('#newLicense').css('color', '#000000');
  //     }
  //
  //   }else{
  //     jQuery('.form-control').css('color', '#000000');
  //   }
  // }

  showPassModal() {
    this.apprPassModal.show();
  }

  showRejectModal() {
    this.apprRejectModal.show();
  }

  showDeleteModal(){
    this.apprDeleteModal.show();
  }

  showTimeModal() {
    this.apprTimeModal.show();
  }



  onHideModal(): void {
    jQuery('.modal-backdrop').remove();
  }

  updateDateRange(event) {
    this.searchForm.startdate = this.date2String(event.beginDate);
    this.searchForm.enddate = this.date2String(event.endDate);
  }

  getStage(event) {
    const startdate = this.date2String(event.beginDate);
    const enddate = this.date2String(event.endDate);
    this.downloadUrlByStage = this.downloadTimeUrl + '?startdate=' + startdate + '&enddate='+ enddate +'&type=企业信息变更';
  }


  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0&&date.month==0&&date.day==0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }

  public pass(comment: string): void {
    this._saveAppr(comment, 'pass', this.apprPassModal);
  }

  public reject(comment: string): void {
    this._saveAppr(comment, 'reject', this.apprRejectModal);
  }

  public apprRejectClose() {
    this._errorMsg = null;
    this.apprRejectModal.hide();
  }

  public apprPassClose() {
    this._errorMsg = null;
    this.apprPassModal.hide();
  }

  public apprDeleteClose(){
    this._errorMsg = null;
    this.apprDeleteModal.hide();
  }

  public apprTimeClose() {
    this._errorMsg = null;
    this.apprTimeModal.hide();
  }

  public delete():void{
    let pkids = [];
    for(let row of this.selectedRowData){
      pkids.push(row.pkid);
    }
    this._service.deleteAppr(this.apprDeleteUrl, pkids)
      .then(res => {
        if (res.status === 'success') {
          this.apprDeleteModal.hide();
          this.dataTable.draw(false);
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }


  private _saveAppr(comment, apprStatus, modal: ModalDirective) {
    let ids = [];
    for (let row of this.selectedRowData) {
      ids.push(row.ids);
    }
    this.apprInfo.ids = ids;

    this.apprInfo.verifydescription = comment;
    this.apprInfo.flag = apprStatus;
    this._service.submitAppr(this.apprUrl, this.apprInfo).then(result => {
      if (result.status === 'success') {
        modal.hide();
        this.apprReviewModal.hide();
        this.dataTable.draw(false);
      } else {
        this._errorMsg = result.data;
      }
    }, error => {
      this._errorMsg = error;
    });
  }
}
